{{ template "page/head_start" .}}
<style>
  body {
    background-color: #f5f7fa;
  }

  .table-card {
    background: white;
    border-radius: 10px;
    box-shadow: 0 2px 8px rgba(0,0,0,.08);
    overflow: hidden;
  }

  .table-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 1.5rem;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .inbound-table {
    width: 100%;
  }

  .inbound-table th {
    background: #f8f9fa;
    padding: 1rem;
    font-weight: 600;
    color: #495057;
    border-bottom: 2px solid #dee2e6;
  }

  .inbound-table td {
    padding: 1rem;
    border-bottom: 1px solid #dee2e6;
    vertical-align: middle;
  }

  .inbound-table tr:hover {
    background-color: #f8f9ff;
  }

  .badge-protocol {
    padding: 6px 12px;
    border-radius: 20px;
    font-size: 0.85rem;
    font-weight: 600;
  }

  .badge-vmess { background: #e3f2fd; color: #1976d2; }
  .badge-vless { background: #f3e5f5; color: #7b1fa2; }
  .badge-trojan { background: #ffebee; color: #c62828; }
  .badge-shadowsocks { background: #e8f5e9; color: #2e7d32; }

  .status-indicator {
    width: 10px;
    height: 10px;
    border-radius: 50%;
    display: inline-block;
    margin-right: 8px;
  }

  .status-enabled { background: #4caf50; box-shadow: 0 0 8px #4caf50; }
  .status-disabled { background: #f44336; }

  .action-btn {
    padding: 6px 12px;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.3s ease;
    margin: 0 2px;
  }

  .action-btn:hover {
    transform: translateY(-2px);
  }

  .btn-edit { background: #2196f3; color: white; }
  .btn-delete { background: #f44336; color: white; }
  .btn-qr { background: #ff9800; color: white; }
  .btn-toggle { background: #9c27b0; color: white; }

  .traffic-bar {
    width: 100%;
    height: 6px;
    background: #e0e0e0;
    border-radius: 3px;
    overflow: hidden;
    margin-top: 4px;
  }

  .traffic-bar-fill {
    height: 100%;
    background: linear-gradient(90deg, #4caf50, #8bc34a);
    transition: width 0.3s ease;
  }

  .modal-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-bottom: none;
  }

  .modal-header .btn-close {
    filter: brightness(0) invert(1);
  }

  .search-box {
    max-width: 300px;
  }

  .empty-state {
    text-align: center;
    padding: 4rem 2rem;
    color: #999;
  }

  .empty-state i {
    font-size: 4rem;
    margin-bottom: 1rem;
    opacity: 0.3;
  }

  .stat-card {
    background: white;
    border-radius: 10px;
    padding: 1.5rem;
    box-shadow: 0 2px 8px rgba(0,0,0,.08);
  }

  .stat-icon {
    width: 50px;
    height: 50px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.5rem;
    color: white;
  }

  .stat-icon.primary { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
  .stat-icon.success { background: linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%); }
  .stat-icon.info { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); }
  .stat-icon.warning { background: linear-gradient(135deg, #ffd89b 0%, #19547b 100%); }

  .stat-value {
    font-size: 2rem;
    font-weight: 700;
    color: #2c3e50;
    margin: 0.5rem 0 0.25rem 0;
  }

  .stat-label {
    color: #7f8c8d;
    font-size: 0.9rem;
    font-weight: 500;
  }

  @media (max-width: 768px) {
    .table-responsive {
      overflow-x: auto;
    }

    .action-btn {
      margin: 2px 0;
      display: block;
      width: 100%;
    }
  }
</style>
{{ template "page/head_end" .}}

{{ template "page/body_start" .}}
{{ template "component/sidebar" . }}

<div class="main-content">
  <!-- Top Navbar -->
  <nav class="navbar-top">
    <div class="d-flex justify-content-between align-items-center flex-wrap">
      <div class="mb-2 mb-md-0">
        <h4 class="mb-0"><i class="bi bi-arrow-down-circle me-2"></i>{{ i18n "menu.inbounds" }}</h4>
        <small class="text-muted">{{ i18n "pages.inbounds.manage" }}</small>
      </div>
      <div class="d-flex gap-2">
        <input type="text" class="form-control search-box" id="searchInput"
               placeholder='{{ i18n "search" }}...'>
        <button class="btn btn-primary" id="addInboundBtn">
          <i class="bi bi-plus-circle me-1"></i> {{ i18n "pages.inbounds.addInbound" }}
        </button>
      </div>
    </div>
  </nav>

  <div class="container-fluid px-4">
    <!-- Stats Row -->
    <div class="row mb-4">
      <div class="col-md-3 col-sm-6 mb-3">
        <div class="stat-card text-center">
          <div class="stat-icon primary mx-auto mb-2">
            <i class="bi bi-list-ul"></i>
          </div>
          <div class="stat-value" id="totalInbounds">0</div>
          <div class="stat-label">{{ i18n "pages.inbounds.total" }}</div>
        </div>
      </div>
      <div class="col-md-3 col-sm-6 mb-3">
        <div class="stat-card text-center">
          <div class="stat-icon success mx-auto mb-2">
            <i class="bi bi-check-circle"></i>
          </div>
          <div class="stat-value" id="enabledInbounds">0</div>
          <div class="stat-label">{{ i18n "pages.inbounds.enabled" }}</div>
        </div>
      </div>
      <div class="col-md-3 col-sm-6 mb-3">
        <div class="stat-card text-center">
          <div class="stat-icon info mx-auto mb-2">
            <i class="bi bi-people"></i>
          </div>
          <div class="stat-value" id="totalClients">0</div>
          <div class="stat-label">{{ i18n "pages.inbounds.clients" }}</div>
        </div>
      </div>
      <div class="col-md-3 col-sm-6 mb-3">
        <div class="stat-card text-center">
          <div class="stat-icon warning mx-auto mb-2">
            <i class="bi bi-arrow-up-right"></i>
          </div>
          <div class="stat-value" id="totalTraffic">0 B</div>
          <div class="stat-label">{{ i18n "pages.inbounds.traffic" }}</div>
        </div>
      </div>
    </div>

    <!-- Inbounds Table -->
    <div class="table-card">
      <div class="table-header">
        <h5 class="mb-0"><i class="bi bi-table me-2"></i>{{ i18n "pages.inbounds.list" }}</h5>
        <button class="btn btn-light btn-sm" id="refreshBtn">
          <i class="bi bi-arrow-clockwise me-1"></i> {{ i18n "refresh" }}
        </button>
      </div>

      <!-- Loading State -->
      <div id="loadingState" class="text-center py-5">
        <div class="spinner-border text-primary"></div>
        <p class="mt-3 text-muted">{{ i18n "loading" }}...</p>
      </div>

      <!-- Table -->
      <div id="tableContainer" style="display: none;">
        <div class="table-responsive">
          <table class="inbound-table" id="inboundsTable">
            <thead>
              <tr>
                <th width="5%">#</th>
                <th width="15%">{{ i18n "pages.inbounds.remark" }}</th>
                <th width="10%">{{ i18n "pages.inbounds.protocol" }}</th>
                <th width="10%">{{ i18n "pages.inbounds.port" }}</th>
                <th width="15%">{{ i18n "pages.inbounds.traffic" }}</th>
                <th width="15%">{{ i18n "pages.inbounds.clients" }}</th>
                <th width="10%">{{ i18n "pages.inbounds.status" }}</th>
                <th width="20%">{{ i18n "pages.inbounds.actions" }}</th>
              </tr>
            </thead>
            <tbody id="inboundsTableBody">
              <!-- Data will be inserted here -->
            </tbody>
          </table>
        </div>

        <!-- Empty State -->
        <div id="emptyState" class="empty-state" style="display: none;">
          <i class="bi bi-inbox"></i>
          <h5>{{ i18n "pages.inbounds.noData" }}</h5>
          <p>{{ i18n "pages.inbounds.addFirst" }}</p>
          <button class="btn btn-primary" onclick="$('#addInboundBtn').click()">
            <i class="bi bi-plus-circle me-1"></i> {{ i18n "pages.inbounds.addInbound" }}
          </button>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Add/Edit Inbound Modal -->
<div class="modal fade" id="inboundModal" tabindex="-1">
  <div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="inboundModalTitle">
          <i class="bi bi-plus-circle me-2"></i>{{ i18n "pages.inbounds.addInbound" }}
        </h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <form id="inboundForm">
          <div class="row">
            <div class="col-md-6 mb-3">
              <label class="form-label">{{ i18n "pages.inbounds.remark" }}</label>
              <input type="text" class="form-control" name="remark" required>
            </div>
            <div class="col-md-6 mb-3">
              <label class="form-label">{{ i18n "pages.inbounds.protocol" }}</label>
              <select class="form-select" name="protocol" required>
                <option value="vmess">VMess</option>
                <option value="vless">VLESS</option>
                <option value="trojan">Trojan</option>
                <option value="shadowsocks">Shadowsocks</option>
                <option value="dokodemo-door">Dokodemo-door</option>
                <option value="http">HTTP</option>
                <option value="socks">SOCKS</option>
              </select>
            </div>
          </div>
          <div class="row">
            <div class="col-md-6 mb-3">
              <label class="form-label">{{ i18n "pages.inbounds.port" }}</label>
              <input type="number" class="form-control" name="port" min="1" max="65535" required>
            </div>
            <div class="col-md-6 mb-3">
              <label class="form-label">{{ i18n "pages.inbounds.listen" }}</label>
              <input type="text" class="form-control" name="listen" placeholder="0.0.0.0">
            </div>
          </div>
          <div class="row">
            <div class="col-md-6 mb-3">
              <label class="form-label">{{ i18n "pages.inbounds.totalTraffic" }} (GB)</label>
              <input type="number" class="form-control" name="total" min="0" value="0">
              <small class="text-muted">0 = {{ i18n "pages.inbounds.unlimited" }}</small>
            </div>
            <div class="col-md-6 mb-3">
              <label class="form-label">{{ i18n "pages.inbounds.expiryTime" }}</label>
              <input type="date" class="form-control" name="expiryTime">
            </div>
          </div>
          <div class="form-check form-switch mb-3">
            <input class="form-check-input" type="checkbox" name="enable" id="enableSwitch" checked>
            <label class="form-check-label" for="enableSwitch">
              {{ i18n "pages.inbounds.enable" }}
            </label>
          </div>
          <input type="hidden" name="id" id="inboundId">
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
          {{ i18n "cancel" }}
        </button>
        <button type="button" class="btn btn-primary" id="saveInboundBtn">
          <i class="bi bi-check-circle me-1"></i> {{ i18n "save" }}
        </button>
      </div>
    </div>
  </div>
</div>

<!-- QR Code Modal -->
<div class="modal fade" id="qrcodeModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title"><i class="bi bi-qr-code me-2"></i>{{ i18n "pages.inbounds.qrcode" }}</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body text-center">
        <div id="qrcodeContainer"></div>
        <div class="mt-3">
          <input type="text" class="form-control" id="shareUrl" readonly>
          <button class="btn btn-sm btn-primary mt-2" onclick="copyToClipboard()">
            <i class="bi bi-clipboard me-1"></i> {{ i18n "copy" }}
          </button>
        </div>
      </div>
    </div>
  </div>
</div>

{{template "page/body_scripts" .}}
<!-- QRCode.js Library -->
<script src="https://cdn.jsdelivr.net/npm/qrcodejs@1.0.0/qrcode.min.js"></script>

<script>
let inbounds = [];
let editingInbound = null;

$(document).ready(function() {
  loadInbounds();

  $('#refreshBtn').on('click', loadInbounds);
  $('#addInboundBtn').on('click', showAddModal);
  $('#saveInboundBtn').on('click', saveInbound);
  $('#searchInput').on('input', filterInbounds);
});

function loadInbounds() {
  $('#loadingState').show();
  $('#tableContainer').hide();

  axios.post('/panel/API/inbounds/list')
    .then(response => {
      if (response.data.success) {
        inbounds = response.data.obj || [];
        renderInbounds(inbounds);
        updateStats();
      }
      $('#loadingState').hide();
      $('#tableContainer').show();
    })
    .catch(error => {
      $('#loadingState').hide();
      console.error('Failed to load inbounds:', error);
    });
}

function renderInbounds(data) {
  const tbody = $('#inboundsTableBody');
  tbody.empty();

  if (data.length === 0) {
    $('#emptyState').show();
    return;
  }

  $('#emptyState').hide();

  data.forEach((inbound, index) => {
    const trafficUsed = inbound.up + inbound.down;
    const trafficPercent = inbound.total > 0 ? (trafficUsed / inbound.total * 100).toFixed(1) : 0;

    const row = `
      <tr data-id="${inbound.id}">
        <td>${index + 1}</td>
        <td><strong>${inbound.remark || '-'}</strong></td>
        <td><span class="badge-protocol badge-${inbound.protocol}">${inbound.protocol.toUpperCase()}</span></td>
        <td><code>${inbound.port}</code></td>
        <td>
          <small>${formatBytes(trafficUsed)} / ${inbound.total > 0 ? formatBytes(inbound.total) : '∞'}</small>
          <div class="traffic-bar">
            <div class="traffic-bar-fill" style="width: ${Math.min(trafficPercent, 100)}%"></div>
          </div>
        </td>
        <td>${inbound.clientStats ? inbound.clientStats.length : 0}</td>
        <td>
          <span class="status-indicator ${inbound.enable ? 'status-enabled' : 'status-disabled'}"></span>
          ${inbound.enable ? '{{ i18n "enabled" }}' : '{{ i18n "disabled" }}'}
        </td>
        <td>
          <button class="action-btn btn-edit" onclick="editInbound(${inbound.id})" title="{{ i18n "edit" }}">
            <i class="bi bi-pencil"></i>
          </button>
          <button class="action-btn btn-qr" onclick="showQRCode(${inbound.id})" title="{{ i18n "pages.inbounds.qrcode" }}">
            <i class="bi bi-qr-code"></i>
          </button>
          <button class="action-btn btn-toggle" onclick="toggleInbound(${inbound.id}, ${!inbound.enable})"
                  title="${inbound.enable ? '{{ i18n "disable" }}' : '{{ i18n "enable" }}'}">
            <i class="bi bi-${inbound.enable ? 'pause' : 'play'}-circle"></i>
          </button>
          <button class="action-btn btn-delete" onclick="deleteInbound(${inbound.id})" title="{{ i18n "delete" }}">
            <i class="bi bi-trash"></i>
          </button>
        </td>
      </tr>
    `;
    tbody.append(row);
  });
}

function updateStats() {
  $('#totalInbounds').text(inbounds.length);
  $('#enabledInbounds').text(inbounds.filter(i => i.enable).length);

  let totalClients = 0;
  let totalTraffic = 0;
  inbounds.forEach(inbound => {
    totalClients += inbound.clientStats ? inbound.clientStats.length : 0;
    totalTraffic += inbound.up + inbound.down;
  });

  $('#totalClients').text(totalClients);
  $('#totalTraffic').text(formatBytes(totalTraffic));
}

function showAddModal() {
  editingInbound = null;
  $('#inboundForm')[0].reset();
  $('#inboundId').val('');
  $('#inboundModalTitle').html('<i class="bi bi-plus-circle me-2"></i>{{ i18n "pages.inbounds.addInbound" }}');
  $('#enableSwitch').prop('checked', true);
  new bootstrap.Modal('#inboundModal').show();
}

function editInbound(id) {
  const inbound = inbounds.find(i => i.id === id);
  if (!inbound) return;

  editingInbound = inbound;
  $('#inboundForm')[0].reset();
  $('#inboundId').val(inbound.id);
  $('input[name="remark"]').val(inbound.remark);
  $('select[name="protocol"]').val(inbound.protocol);
  $('input[name="port"]').val(inbound.port);
  $('input[name="listen"]').val(inbound.listen);
  $('input[name="total"]').val(inbound.total / (1024 * 1024 * 1024));
  $('#enableSwitch').prop('checked', inbound.enable);

  $('#inboundModalTitle').html('<i class="bi bi-pencil me-2"></i>{{ i18n "edit" }}');
  new bootstrap.Modal('#inboundModal').show();
}

function saveInbound() {
  const form = $('#inboundForm')[0];
  if (!form.checkValidity()) {
    form.reportValidity();
    return;
  }

  const data = {
    id: parseInt($('#inboundId').val()) || 0,
    remark: $('input[name="remark"]').val(),
    protocol: $('select[name="protocol"]').val(),
    port: parseInt($('input[name="port"]').val()),
    listen: $('input[name="listen"]').val(),
    total: parseInt($('input[name="total"]').val()) * 1024 * 1024 * 1024,
    enable: $('#enableSwitch').is(':checked'),
    settings: '{}',
    streamSettings: '{}',
    sniffing: '{}'
  };

  const url = data.id > 0 ? `/panel/API/inbound/update/${data.id}` : '/panel/API/inbound/add';

  axios.post(url, data)
    .then(response => {
      if (response.data.success) {
        showNotification('{{ i18n "success" }}', 'success');
        bootstrap.Modal.getInstance('#inboundModal').hide();
        loadInbounds();
      }
    })
    .catch(error => {
      console.error('Failed to save inbound:', error);
    });
}

function deleteInbound(id) {
  if (!confirm('{{ i18n "pages.inbounds.deleteConfirm" }}')) return;

  axios.post(`/panel/API/inbound/del/${id}`)
    .then(response => {
      if (response.data.success) {
        showNotification('{{ i18n "deleted" }}', 'success');
        loadInbounds();
      }
    });
}

function toggleInbound(id, enable) {
  const inbound = inbounds.find(i => i.id === id);
  if (!inbound) return;

  inbound.enable = enable;
  axios.post(`/panel/API/inbound/update/${id}`, inbound)
    .then(response => {
      if (response.data.success) {
        loadInbounds();
      }
    });
}

function showQRCode(id) {
  // Placeholder - would need actual URL generation logic
  const url = `vmess://example${id}`;
  $('#shareUrl').val(url);

  $('#qrcodeContainer').empty();
  new QRCode($('#qrcodeContainer')[0], {
    text: url,
    width: 256,
    height: 256
  });

  new bootstrap.Modal('#qrcodeModal').show();
}

function copyToClipboard() {
  const input = $('#shareUrl')[0];
  input.select();
  document.execCommand('copy');
  showNotification('{{ i18n "copied" }}', 'success');
}

function filterInbounds() {
  const search = $('#searchInput').val().toLowerCase();
  if (!search) {
    renderInbounds(inbounds);
    return;
  }

  const filtered = inbounds.filter(inbound =>
    inbound.remark.toLowerCase().includes(search) ||
    inbound.protocol.toLowerCase().includes(search) ||
    inbound.port.toString().includes(search)
  );

  renderInbounds(filtered);
}

function formatBytes(bytes) {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return Math.round((bytes / Math.pow(k, i)) * 100) / 100 + ' ' + sizes[i];
}
</script>
{{ template "page/body_end" .}}
